package server.service;

import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.apache.shardingsphere.transaction.core.TransactionTypeHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import server.dao.OrderDao;
import server.enitity.Order;

import javax.transaction.Transactional;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName OrderService
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2021/12/20 上午12:11
 * @Version V1.0
 * @Since JDK 11
 */
@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional(rollbackOn = Exception.class)
    @ShardingTransactionType(TransactionType.XA)  // 支持TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
    public void transaction(List<Order> list){
        batchOrder(list);
    }

    public void batchOrder(List<Order> list){
        jdbcTemplate.batchUpdate("INSERT INTO `study`.`t_order`(`id`, `user_id`, `item_id`, `count`, `price_sum`, `price`, `pay_price`, `create_time`, `update_time`, `pay_type`, `order_ip`, `app_id`, `app_version`, `order_no`, `bussiness_id`, `status`, `app_platform`, `device`, `item_name`, `finish_time`) VALUES (?, ?, ?, ?, ?,?, NULL, ?, ?, NULL, NULL, NULL, NULL, ?, ?, ?, NULL, NULL, ?, NULL);",
                new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        Order order = list.get(i);
                        ps.setLong(1,order.getId());
                        ps.setInt(2,order.getUserId());
                        ps.setInt(3,order.getItemId());
                        ps.setInt(4,order.getCount());
                        ps.setBigDecimal(5,order.getPriceSum());
                        ps.setBigDecimal(6,order.getPrice());

                        ps.setDate(7, new Date(order.getCreateTime().getTime()));
                        ps.setDate(8,new Date(order.getUpdateTime().getTime()));
                        ps.setString(9,order.getOrderNo());
                        ps.setString(10,order.getBussinessId());
                        ps.setInt(11,order.getStatus());
                        ps.setString(12,order.getItemName());
                    }

                    @Override
                    public int getBatchSize() {
                        return list.size();
                    }
                });
    }
}
